function b() {
  let r = new TextDecoder('utf-8')
  return {
    concat(e, t) {
      let n = new Uint8Array(e.length + t.length)
      return n.set(e), n.set(t, e.length), n
    },
    copy(e, t, n) {
      let i = new Uint8Array(n - t)
      return i.set(e.subarray(t, n)), i
    },
    toUtf8String(e, t, n) {
      return r.decode(e.subarray(t, n))
    }
  }
}
function R(r, e) {
  let t = e != null ? e : b(),
    n,
    i = !1,
    s = !1,
    o = !1,
    a
  function l(f) {
    let c,
      d = 0
    for (n ? ((c = f.length === 0 ? 0 : n.length), (f = t.concat(n, f))) : (c = 0); c < f.length; ) {
      let g = f[c]
      if (g === 10) {
        if (!s) {
          let D = c > 0 && f[c - 1] === 13 ? c - 1 : c
          if (i) return
          if (((o = r.next(t.toUtf8String(f, d, D)) === !1), (d = c + 1), o)) break
        }
      } else g === 34 && (s = !s)
      c++
    }
    if ((d < f.length ? (n = t.copy(f, d, f.length)) : (n = void 0), o)) {
      if (r.useResume) {
        r.useResume(() => {
          ;(o = !1), l(new Uint8Array(0))
        })
        return
      }
      u.error(new Error('Unable to pause, useResume is not configured!')), (o = !1)
    }
    a && (a(), (a = void 0))
  }
  let u = {
    next(f) {
      if (!i)
        try {
          return l(f), !o
        } catch (c) {
          this.error(c)
        }
      return !0
    },
    error(f) {
      i || ((i = !0), r.error(f))
    },
    complete() {
      i || (n && r.next(t.toUtf8String(n, 0, n.length)), (i = !0), r.complete())
    }
  }
  return (
    r.useCancellable &&
      (u.useCancellable = f => {
        r.useCancellable &&
          r.useCancellable({
            cancel() {
              f.cancel(), (n = void 0), u.complete()
            },
            isCancelled() {
              return f.isCancelled()
            }
          })
      }),
    r.useResume &&
      (u.useResume = f => {
        a = f
      }),
    u
  )
}
async function* H(r, e) {
  let t = e != null ? e : b(),
    n,
    i = !1
  for await (let s of r) {
    let o,
      a = 0
    for (n ? ((o = n.length), (s = t.concat(n, s))) : (o = 0); o < s.length; ) {
      let l = s[o]
      if (l === 10) {
        if (!i) {
          let u = o > 0 && s[o - 1] === 13 ? o - 1 : o
          yield t.toUtf8String(s, a, u), (a = o + 1)
        }
      } else l === 34 && (i = !i)
      o++
    }
    a < s.length ? (n = t.copy(s, a, s.length)) : (n = void 0)
  }
  n && (yield t.toUtf8String(n, 0, n.length))
}
var x = class {
  constructor() {
    this._reuse = !1
  }
  get reuse() {
    return this._reuse
  }
  set reuse(e) {
    e && !this.reusedValues && (this.reusedValues = new Array(10)), (this._reuse = e)
  }
  withReuse() {
    return (this.reuse = !0), this
  }
  splitLine(e) {
    if (e == null) return (this.lastSplitLength = 0), []
    let t = 0,
      n = 0,
      i = this._reuse ? this.reusedValues : [],
      s = 0
    for (let a = 0; a < e.length; a++) {
      let l = e[a]
      if (l === ',') {
        if (t % 2 === 0) {
          let u = this.getValue(e, n, a, t)
          this._reuse ? (i[s++] = u) : i.push(u), (n = a + 1), (t = 0)
        }
      } else l === '"' && t++
    }
    let o = this.getValue(e, n, e.length, t)
    return (
      this._reuse ? ((i[s] = o), (this.lastSplitLength = s + 1)) : (i.push(o), (this.lastSplitLength = i.length)), i
    )
  }
  getValue(e, t, n, i) {
    return t === e.length
      ? ''
      : i === 0
      ? e.substring(t, n)
      : i === 2
      ? e.substring(t + 1, n - 1)
      : e.substring(t + 1, n - 1).replace(/""/gi, '"')
  }
}
var V = r => r,
  C = {
    boolean: r => (r === '' ? null : r === 'true'),
    unsignedLong: r => (r === '' ? null : +r),
    long: r => (r === '' ? null : +r),
    double(r) {
      switch (r) {
        case '':
          return null
        case '+Inf':
          return Number.POSITIVE_INFINITY
        case '-Inf':
          return Number.NEGATIVE_INFINITY
        default:
          return +r
      }
    },
    string: V,
    base64Binary: V,
    duration: r => (r === '' ? null : r),
    'dateTime:RFC3339': r => (r === '' ? null : r)
  },
  P = class {
    get(e) {
      var n
      let t = e[this.index]
      return (
        (t === '' || t === void 0) && this.defaultValue && (t = this.defaultValue),
        ((n = C[this.dataType]) != null ? n : V)(t)
      )
    }
  },
  ee = Object.freeze({
    label: '',
    dataType: '',
    group: !1,
    defaultValue: '',
    index: Number.MAX_SAFE_INTEGER,
    get: () => {}
  })
function F() {
  return new P()
}
function We(r) {
  var t, n
  let e = new P()
  return (
    (e.label = String(r.label)),
    (e.dataType = r.dataType),
    (e.group = !!r.group),
    (e.defaultValue = (t = r.defaultValue) != null ? t : ''),
    (e.index = (n = r.index) != null ? n : 0),
    e
  )
}
var Ce = [404, 408, 425, 429, 500, 502, 503, 504]
function Oe(r) {
  return Ce.includes(r)
}
var y = class r extends Error {
    constructor(e) {
      super(e), (this.name = 'IllegalArgumentError'), Object.setPrototypeOf(this, r.prototype)
    }
  },
  h = class r extends Error {
    constructor(t, n, i, s, o, a, l) {
      super()
      this.statusCode = t
      this.statusMessage = n
      this.body = i
      this.contentType = o
      if ((Object.setPrototypeOf(this, r.prototype), (this.headers = l), a)) this.message = a
      else if (i) {
        if (o != null && o.startsWith('application/json'))
          try {
            ;(this.json = JSON.parse(i)), (this.message = this.json.message), (this.code = this.json.code)
          } catch (u) {}
        this.message || (this.message = `${t} ${n} : ${i}`)
      } else this.message = `${t} ${n}`
      ;(this.name = 'HttpError'), this.setRetryAfter(s)
    }
    setRetryAfter(t) {
      typeof t == 'string'
        ? /^[0-9]+$/.test(t)
          ? (this._retryAfter = parseInt(t))
          : (this._retryAfter = 0)
        : (this._retryAfter = 0)
    }
    canRetry() {
      return Oe(this.statusCode)
    }
    retryAfter() {
      return this._retryAfter
    }
  },
  Se = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'EPIPE']
function Ne(r) {
  if (r) {
    if (typeof r.canRetry == 'function') return !!r.canRetry()
    if (r.code && Se.includes(r.code)) return !0
  } else return !1
  return !1
}
function re(r, e) {
  if (r) {
    let t
    return typeof r.retryAfter == 'function'
      ? r.retryAfter()
      : ((t = 0), e && e > 0 ? t + Math.round(Math.random() * e) : t)
  } else return 0
}
var te = class r extends Error {
    constructor() {
      super(),
        Object.setPrototypeOf(this, r.prototype),
        (this.name = 'RequestTimedOutError'),
        (this.message = 'Request timed out')
    }
    canRetry() {
      return !0
    }
    retryAfter() {
      return 0
    }
  },
  L = class r extends Error {
    constructor() {
      super(), (this.name = 'AbortError'), Object.setPrototypeOf(this, r.prototype), (this.message = 'Response aborted')
    }
    canRetry() {
      return !0
    }
    retryAfter() {
      return 0
    }
  }
function Xe() {
  C['dateTime:RFC3339'] = r => (r === '' ? null : new Date(Date.parse(r)))
}
function Ge() {
  C['dateTime:RFC3339'] = r => (r === '' ? null : Date.parse(r))
}
function Ke() {
  C['dateTime:RFC3339'] = r => (r === '' ? null : r)
}
var z = class {
  constructor(e) {
    e.forEach((t, n) => (t.index = n)), (this.columns = e)
  }
  column(e, t = !0) {
    for (let n = 0; n < this.columns.length; n++) {
      let i = this.columns[n]
      if (i.label === e) return i
    }
    if (t) throw new y(`Column ${e} not found!`)
    return ee
  }
  toObject(e) {
    let t = {}
    for (let n = 0; n < this.columns.length && n < e.length; n++) {
      let i = this.columns[n]
      t[i.label] = i.get(e)
    }
    return t
  }
  get(e, t) {
    return this.column(t, !1).get(e)
  }
}
function I(r) {
  return new z(r)
}
function W(r) {
  let e = new x().withReuse(),
    t,
    n = !0,
    i = 0,
    s,
    o = {
      error(a) {
        r.error(a)
      },
      next(a) {
        if (a === '') (n = !0), (t = void 0)
        else {
          let l = e.splitLine(a),
            u = e.lastSplitLength
          if (n) {
            if (!t) {
              t = new Array(u)
              for (let f = 0; f < u; f++) t[f] = F()
            }
            if (l[0].startsWith('#')) {
              if (l[0] === '#datatype') for (let f = 1; f < u; f++) t[f].dataType = l[f]
              else if (l[0] === '#default') for (let f = 1; f < u; f++) t[f].defaultValue = l[f]
              else if (l[0] === '#group') for (let f = 1; f < u; f++) t[f].group = l[f][0] === 't'
            } else {
              l[0] === '' ? ((i = 1), (t = t.slice(1))) : (i = 0)
              for (let f = i; f < u; f++) t[f - i].label = l[f]
              ;(s = I(t)), (n = !1)
            }
          } else return r.next(l.slice(i, u), s)
        }
        return !0
      },
      complete() {
        r.complete()
      }
    }
  return (
    r.useCancellable && (o.useCancellable = r.useCancellable.bind(r)),
    r.useResume && (o.useResume = r.useResume.bind(r)),
    o
  )
}
async function* ne(r) {
  let e = new x().withReuse(),
    t,
    n = !0,
    i = 0,
    s
  for await (let o of r)
    if (o === '') (n = !0), (t = void 0)
    else {
      let a = e.splitLine(o),
        l = e.lastSplitLength
      if (n) {
        if (!t) {
          t = new Array(l)
          for (let u = 0; u < l; u++) t[u] = F()
        }
        if (a[0].startsWith('#')) {
          if (a[0] === '#datatype') for (let u = 1; u < l; u++) t[u].dataType = a[u]
          else if (a[0] === '#default') for (let u = 1; u < l; u++) t[u].defaultValue = a[u]
          else if (a[0] === '#group') for (let u = 1; u < l; u++) t[u].group = a[u][0] === 't'
        } else {
          a[0] === '' ? ((i = 1), (t = t.slice(1))) : (i = 0)
          for (let u = i; u < l; u++) t[u - i].label = a[u]
          ;(s = I(t)), (n = !1)
        }
      } else yield { values: a.slice(i, l), tableMeta: s }
    }
}
function pt(r, e) {
  let t = !1,
    n = 0,
    i = 0
  for (; i < r.length; ) {
    let s = r.charCodeAt(i)
    if (s === 10) {
      if (!t) {
        let o = i > 0 && r.charCodeAt(i - 1) === 13 ? i - 1 : i
        e.next(r.substring(n, o)), (n = i + 1)
      }
    } else s === 34 && (t = !t)
    i++
  }
  n < i && e.next(r.substring(n, i)), e.complete()
}
var ie = (typeof Symbol == 'function' && Symbol.observable) || '@@observable'
var N = class {
  constructor(e, t) {
    this.isClosed = !1
    try {
      t({
        next: n => {
          e.next(n)
        },
        error: n => {
          ;(this.isClosed = !0), e.error(n)
        },
        complete: () => {
          ;(this.isClosed = !0), e.complete()
        },
        useCancellable: n => {
          this.cancellable = n
        }
      })
    } catch (n) {
      ;(this.isClosed = !0), e.error(n)
    }
  }
  get closed() {
    return this.isClosed
  }
  unsubscribe() {
    var e
    ;(e = this.cancellable) == null || e.cancel(), (this.isClosed = !0)
  }
}
function k() {}
function ve(r) {
  let { next: e, error: t, complete: n } = r
  return { next: e ? e.bind(r) : k, error: t ? t.bind(r) : k, complete: n ? n.bind(r) : k }
}
var T = class {
  constructor(e, t) {
    this.executor = e
    this.decorator = t
  }
  subscribe(e, t, n) {
    let i = ve(typeof e != 'object' || e === null ? { next: e, error: t, complete: n } : e)
    return new N(this.decorator(i), this.executor)
  }
  [ie]() {
    return this
  }
}
var Nt = { timeout: 1e4 },
  se = { retryJitter: 200, minRetryDelay: 5e3, maxRetryDelay: 125e3, exponentialBase: 5, randomRetry: !0 },
  oe = {
    batchSize: 1e3,
    maxBatchBytes: 5e7,
    flushInterval: 6e4,
    writeFailed: function () {},
    writeSuccess: function () {},
    writeRetrySkipped: function () {},
    maxRetries: 5,
    maxRetryTime: 18e4,
    maxBufferLines: 32e3,
    retryJitter: 200,
    minRetryDelay: 5e3,
    maxRetryDelay: 125e3,
    exponentialBase: 2,
    gzipThreshold: 1e3,
    randomRetry: !0
  }
function Q(r, e) {
  return function (t) {
    let n = '',
      i = 0,
      s = 0
    for (; s < t.length; ) {
      let o = r.indexOf(t[s])
      o >= 0 && ((n += t.substring(i, s)), (n += e[o]), (i = s + 1)), s++
    }
    return i == 0 ? t : (i < t.length && (n += t.substring(i, t.length)), n)
  }
}
function Ae(r, e) {
  let t = Q(r, e)
  return n => '"' + t(n) + '"'
}
var w = {
  measurement: Q(
    `, 
\r	`,
    ['\\,', '\\ ', '\\n', '\\r', '\\t']
  ),
  quoted: Ae('"\\', ['\\"', '\\\\']),
  tag: Q(
    `, =
\r	`,
    ['\\,', '\\ ', '\\=', '\\n', '\\r', '\\t']
  )
}
var ce = '000000000'
function De(r) {
  return !1
}
De(!0)
var ae = Date.now(),
  j = 0
function q() {
  {
    let r = Date.now()
    r !== ae ? ((ae = r), (j = 0)) : j++
    let e = String(j)
    return String(r) + ce.substr(0, 6 - e.length) + e
  }
}
function le() {
  return String(Date.now()) + ce.substr(0, 3)
}
function ue() {
  return String(Date.now())
}
function fe() {
  return String(Math.floor(Date.now() / 1e3))
}
var de = { s: fe, ms: ue, us: le, ns: q, seconds: fe, millis: ue, micros: le, nanos: q },
  me = {
    s: r => `${Math.floor(r.getTime() / 1e3)}`,
    ms: r => `${r.getTime()}`,
    us: r => `${r.getTime()}000`,
    ns: r => `${r.getTime()}000000`
  }
function pe(r) {
  return r === void 0
    ? q()
    : typeof r == 'string'
    ? r.length > 0
      ? r
      : void 0
    : r instanceof Date
    ? `${r.getTime()}000000`
    : String(typeof r == 'number' ? Math.floor(r) : r)
}
var Ee = {
    error(r, e) {
      console.error('ERROR: ' + r, e || '')
    },
    warn(r, e) {
      console.warn('WARN: ' + r, e || '')
    }
  },
  U = Ee,
  m = {
    error(r, e) {
      U.error(r, e)
    },
    warn(r, e) {
      U.warn(r, e)
    }
  }
function Jt(r) {
  let e = U
  return (U = r), e
}
var $ = Symbol('FLUX_VALUE'),
  p = class {
    constructor(e) {
      this.fluxValue = e
    }
    toString() {
      return this.fluxValue
    }
    [$]() {
      return this.fluxValue
    }
  }
function Pe(r) {
  return typeof r == 'object' && typeof r[$] == 'function'
}
function O(r) {
  if (r == null) return ''
  r = r.toString()
  let e,
    t = 0
  function n() {
    e === void 0 && (e = r.substring(0, t))
  }
  for (; t < r.length; t++) {
    let i = r.charAt(t)
    switch (i) {
      case '\r':
        n(), (e += '\\r')
        break
      case `
`:
        n(), (e += '\\n')
        break
      case '	':
        n(), (e += '\\t')
        break
      case '"':
      case '\\':
        n(), (e = e + '\\' + i)
        break
      case '$':
        if (t + 1 < r.length && r.charAt(t + 1) === '{') {
          n(), t++, (e += '\\${')
          break
        }
        e != null && (e += i)
        break
      default:
        e != null && (e += i)
    }
  }
  return e !== void 0 ? e : r
}
function Gt(r) {
  return new p(`"${O(r)}"`)
}
function ye(r) {
  let e = Number(r)
  if (!isFinite(e)) {
    if (typeof r == 'number') return `float(v: "${e}")`
    throw new Error(`not a flux float: ${r}`)
  }
  let t = e.toString(),
    n = !1
  for (let i of t)
    if (!((i >= '0' && i <= '9') || i == '-')) {
      if (i === '.') {
        n = !0
        continue
      }
      return `float(v: "${t}")`
    }
  return n ? t : t + '.0'
}
function Kt(r) {
  return new p(ye(r))
}
function ge(r) {
  let e = String(r),
    t = e.startsWith('-'),
    n = t ? e.substring(1) : e
  if (n.length === 0 || n.length > 19) throw new Error(`not a flux integer: ${e}`)
  for (let i of n) if (i < '0' || i > '9') throw new Error(`not a flux integer: ${e}`)
  if (n.length === 19) {
    if (t && n > '9223372036854775808') throw new Error(`flux integer out of bounds: ${e}`)
    if (!t && n > '9223372036854775807') throw new Error(`flux integer out of bounds: ${e}`)
  }
  return e
}
function Yt(r) {
  return new p(ge(r))
}
function Fe(r) {
  return `time(v: "${O(r)}")`
}
function Zt(r) {
  return new p(Fe(r))
}
function er(r) {
  return new p(`duration(v: "${O(r)}")`)
}
function be(r) {
  return r instanceof RegExp ? r.toString() : new RegExp(r).toString()
}
function tr(r) {
  return new p(be(r))
}
function rr(r) {
  return r === 'true' || r === 'false' ? new p(r) : new p((!!r).toString())
}
function he(r) {
  return new p(String(r))
}
function J(r) {
  if (r === void 0) return ''
  if (r === null) return 'null'
  if (typeof r == 'boolean') return r.toString()
  if (typeof r == 'string') return `"${O(r)}"`
  if (typeof r == 'number') return Number.isSafeInteger(r) ? ge(r) : ye(r)
  if (typeof r == 'object') {
    if (typeof r[$] == 'function') return r[$]()
    if (r instanceof Date) return r.toISOString()
    if (r instanceof RegExp) return be(r)
    if (Array.isArray(r)) return `[${r.map(J).join(',')}]`
  } else if (typeof r == 'bigint') return `${r}.0`
  return J(r.toString())
}
function nr(r, ...e) {
  if (r.length == 1 && e.length === 0) return he(r[0])
  let t = new Array(r.length + e.length),
    n = 0
  for (let i = 0; i < r.length; i++) {
    let s = r[i]
    if (((t[n++] = s), i < e.length)) {
      let o = e[i],
        a
      if (s.endsWith('"') && i + 1 < r.length && r[i + 1].startsWith('"')) a = O(o)
      else if (((a = J(o)), a === '' && !Pe(o)))
        throw new Error(`Unsupported parameter literal '${o}' at index: ${i}, type: ${typeof o}`)
      t[n++] = a
    } else if (i < r.length - 1) throw new Error('Too few parameters supplied!')
  }
  return he(t.join(''))
}
var xe = class {
  constructor(e) {
    this.tags = {}
    this.fields = {}
    e && (this.name = e)
  }
  measurement(e) {
    return (this.name = e), this
  }
  tag(e, t) {
    return (this.tags[e] = t), this
  }
  booleanField(e, t) {
    return (this.fields[e] = t ? 'T' : 'F'), this
  }
  intField(e, t) {
    let n
    if (
      (typeof t == 'number' ? (n = t) : (n = parseInt(String(t))),
      isNaN(n) || n <= -9223372036854776e3 || n >= 9223372036854776e3)
    )
      throw new Error(`invalid integer value for field '${e}': '${t}'!`)
    return (this.fields[e] = `${Math.floor(n)}i`), this
  }
  uintField(e, t) {
    if (typeof t == 'number') {
      if (isNaN(t) || t < 0 || t > Number.MAX_SAFE_INTEGER)
        throw new Error(`uint value for field '${e}' out of range: ${t}`)
      this.fields[e] = `${Math.floor(t)}u`
    } else {
      let n = String(t)
      for (let i = 0; i < n.length; i++) {
        let s = n.charCodeAt(i)
        if (s < 48 || s > 57) throw new Error(`uint value has an unsupported character at pos ${i}: ${t}`)
      }
      if (n.length > 20 || (n.length === 20 && n.localeCompare('18446744073709551615') > 0))
        throw new Error(`uint value for field '${e}' out of range: ${n}`)
      this.fields[e] = `${n}u`
    }
    return this
  }
  floatField(e, t) {
    let n
    if ((typeof t == 'number' ? (n = t) : (n = parseFloat(t)), !isFinite(n)))
      throw new Error(`invalid float value for field '${e}': ${t}`)
    return (this.fields[e] = String(n)), this
  }
  stringField(e, t) {
    return t != null && (typeof t != 'string' && (t = String(t)), (this.fields[e] = w.quoted(t))), this
  }
  timestamp(e) {
    return (this.time = e), this
  }
  toLineProtocol(e) {
    if (!this.name) return
    let t = ''
    if (
      (Object.keys(this.fields)
        .sort()
        .forEach(o => {
          if (o) {
            let a = this.fields[o]
            t.length > 0 && (t += ','), (t += `${w.tag(o)}=${a}`)
          }
        }),
      t.length === 0)
    )
      return
    let n = '',
      i = e && e.defaultTags ? { ...e.defaultTags, ...this.tags } : this.tags
    Object.keys(i)
      .sort()
      .forEach(o => {
        if (o) {
          let a = i[o]
          a && ((n += ','), (n += `${w.tag(o)}=${w.tag(a)}`))
        }
      })
    let s = this.time
    return (
      e && e.convertTime ? (s = e.convertTime(s)) : (s = pe(s)),
      `${w.measurement(this.name)}${n} ${t}${s !== void 0 ? ' ' + s : ''}`
    )
  }
  toString() {
    let e = this.toLineProtocol(void 0)
    return e || `invalid point: ${JSON.stringify(this, void 0)}`
  }
}
var X = class {
  constructor(e) {
    ;(this.options = { ...se, ...e }), this.success()
  }
  nextDelay(e, t) {
    let n = re(e)
    if (n && n > 0) return n + Math.round(Math.random() * this.options.retryJitter)
    if (t && t > 0) {
      if (this.options.randomRetry) {
        let s = Math.max(this.options.minRetryDelay, 1),
          o = s * this.options.exponentialBase
        for (let a = 1; a < t; a++)
          if (((s = o), (o = o * this.options.exponentialBase), o >= this.options.maxRetryDelay)) {
            o = this.options.maxRetryDelay
            break
          }
        return s + Math.round(Math.random() * (o - s) + Math.random() * this.options.retryJitter)
      }
      let i = Math.max(this.options.minRetryDelay, 1)
      for (let s = 1; s < t; s++)
        if (((i = i * this.options.exponentialBase), i >= this.options.maxRetryDelay)) {
          i = this.options.maxRetryDelay
          break
        }
      return i + Math.round(Math.random() * this.options.retryJitter)
    } else
      this.currentDelay
        ? (this.currentDelay = Math.min(
            Math.max(this.currentDelay * this.options.exponentialBase, 1) +
              Math.round(Math.random() * this.options.retryJitter),
            this.options.maxRetryDelay
          ))
        : (this.currentDelay = this.options.minRetryDelay + Math.round(Math.random() * this.options.retryJitter))
    return this.currentDelay
  }
  success() {
    this.currentDelay = void 0
  }
}
function Te(r) {
  return new X(r)
}
function Le(r) {
  let e,
    t = r,
    n = r
  for (; n.next; ) n.next.expires < t.expires && ((e = n), (t = n.next)), (n = n.next)
  return [t, e]
}
var S = class {
  constructor(e, t, n = () => {}) {
    this.maxLines = e
    this.retryLines = t
    this.onShrink = n
    this.size = 0
    this.closed = !1
    this._timeoutHandle = void 0
  }
  addLines(e, t, n, i) {
    if (this.closed || !e.length) return
    let s = Date.now() + n
    if ((i < s && (s = i), this.first && this.size + e.length > this.maxLines)) {
      let u = this.size,
        f = u * 0.7
      do {
        let [c, d] = Le(this.first)
        ;(this.size -= c.lines.length),
          d
            ? (d.next = c.next)
            : ((this.first = c.next), this.first && this.scheduleRetry(this.first.retryTime - Date.now())),
          (c.next = void 0),
          this.onShrink(c)
      } while (this.first && this.size + e.length > f)
      m.error(
        `RetryBuffer: ${u - this.size} oldest lines removed to keep buffer size under the limit of ${
          this.maxLines
        } lines.`
      )
    }
    let o = { lines: e, retryCount: t, retryTime: s, expires: i },
      a = this.first,
      l
    for (;;) {
      if (!a || a.retryTime > s) {
        ;(o.next = a), l ? (l.next = o) : ((this.first = o), this.scheduleRetry(s - Date.now()))
        break
      }
      ;(l = a), (a = a.next)
    }
    this.size += e.length
  }
  removeLines() {
    if (this.first) {
      let e = this.first
      return (this.first = this.first.next), (e.next = void 0), (this.size -= e.lines.length), e
    }
  }
  scheduleRetry(e) {
    this._timeoutHandle && clearTimeout(this._timeoutHandle),
      (this._timeoutHandle = setTimeout(() => {
        let t = this.removeLines()
        t
          ? this.retryLines(t.lines, t.retryCount, t.expires)
              .catch(() => {})
              .finally(() => {
                this.first && this.scheduleRetry(this.first.retryTime - Date.now())
              })
          : (this._timeoutHandle = void 0)
      }, Math.max(e, 0)))
  }
  async flush() {
    let e
    for (; (e = this.removeLines()); ) await this.retryLines(e.lines, e.retryCount, e.expires)
  }
  close() {
    return (
      this._timeoutHandle && (clearTimeout(this._timeoutHandle), (this._timeoutHandle = void 0)),
      (this.closed = !0),
      this.size
    )
  }
}
function G(r) {
  let e = r.length
  for (let t = 0; t < r.length; t++) {
    let n = r.charCodeAt(t)
    n < 128 ||
      (n >= 128 && n <= 2047 ? e++ : n >= 2048 && n <= 65535 ? (n >= 55296 && n <= 57343 ? e++ : (e += 2)) : (e += 3))
  }
  return e
}
var K = class {
    constructor(e, t, n, i) {
      this.maxChunkRecords = e
      this.maxBatchBytes = t
      this.flushFn = n
      this.scheduleSend = i
      this.length = 0
      this.bytes = -1
      this.lines = new Array(e)
    }
    add(e) {
      let t = G(e)
      this.length === 0 ? this.scheduleSend() : this.bytes + t + 1 >= this.maxBatchBytes && this.flush().catch(n => {}),
        (this.lines[this.length] = e),
        this.length++,
        (this.bytes += t + 1),
        (this.length >= this.maxChunkRecords || this.bytes >= this.maxBatchBytes) && this.flush().catch(n => {})
    }
    flush() {
      let e = this.reset()
      return e.length > 0 ? this.flushFn(e) : Promise.resolve()
    }
    reset() {
      let e = this.lines.slice(0, this.length)
      return (this.length = 0), (this.bytes = -1), e
    }
  },
  v = class {
    constructor(e, t, n, i, s) {
      this.transport = e
      this.closed = !1
      this._timeoutHandle = void 0
      ;(this.path = `/api/v2/write?org=${encodeURIComponent(t)}&bucket=${encodeURIComponent(n)}&precision=${i}`),
        s != null && s.consistency && (this.path += `&consistency=${encodeURIComponent(s.consistency)}`),
        (this.writeOptions = { ...oe, ...s }),
        (this.currentTime = de[i]),
        (this.dateToProtocolTimestamp = me[i]),
        this.writeOptions.defaultTags && this.useDefaultTags(this.writeOptions.defaultTags),
        (this.sendOptions = {
          method: 'POST',
          headers: { 'content-type': 'text/plain; charset=utf-8', ...(s == null ? void 0 : s.headers) },
          gzipThreshold: this.writeOptions.gzipThreshold
        })
      let o = () => {
        this.writeOptions.flushInterval > 0 &&
          (this._clearFlushTimeout(),
          this.closed ||
            (this._timeoutHandle = setTimeout(
              () => this.sendBatch(this.writeBuffer.reset(), this.writeOptions.maxRetries).catch(a => {}),
              this.writeOptions.flushInterval
            )))
      }
      ;(this.writeBuffer = new K(
        this.writeOptions.batchSize,
        this.writeOptions.maxBatchBytes,
        a => (this._clearFlushTimeout(), this.sendBatch(a, this.writeOptions.maxRetries)),
        o
      )),
        (this.sendBatch = this.sendBatch.bind(this)),
        (this.retryStrategy = Te(this.writeOptions)),
        (this.retryBuffer = new S(
          this.writeOptions.maxBufferLines,
          this.sendBatch,
          this.writeOptions.writeRetrySkipped
        ))
    }
    sendBatch(e, t, n = Date.now() + this.writeOptions.maxRetryTime) {
      let i = this,
        s = i.writeOptions.maxRetries + 1 - t
      if (!this.closed && e.length > 0) {
        if (n <= Date.now()) {
          let o = new Error('Max retry time exceeded.'),
            a = i.writeOptions.writeFailed.call(i, o, e, s, n)
          return a || (m.error(`Write to InfluxDB failed (attempt: ${s}).`, o), Promise.reject(o))
        }
        return new Promise((o, a) => {
          let l,
            u,
            f = {
              responseStarted(c, d) {
                ;(l = d), (u = c)
              },
              error(c) {
                let d = i.writeOptions.writeFailed.call(i, c, e, s, n)
                if (d) {
                  d.then(o, a)
                  return
                }
                if (
                  c instanceof h &&
                  c.json &&
                  typeof c.json.error == 'string' &&
                  c.json.error.includes('hinted handoff queue not empty')
                ) {
                  m.warn('Write to InfluxDB returns: ' + c.json.error), (l = 204), f.complete()
                  return
                }
                if (!i.closed && t > 0 && (!(c instanceof h) || c.statusCode >= 429)) {
                  m.warn(`Write to InfluxDB failed (attempt: ${s}).`, c),
                    i.retryBuffer.addLines(e, t - 1, i.retryStrategy.nextDelay(c, s), n),
                    a(c)
                  return
                }
                m.error('Write to InfluxDB failed.', c), a(c)
              },
              complete() {
                if (l == 204 || l == 201 || l == null)
                  i.writeOptions.writeSuccess.call(i, e), i.retryStrategy.success(), o()
                else {
                  let c = `204 HTTP response status code expected, but ${l} returned`,
                    d = new h(l, c, void 0, '0', void 0, void 0, u)
                  ;(d.message = c), f.error(d)
                }
              }
            }
          this.transport.send(
            this.path,
            e.join(`
`),
            this.sendOptions,
            f
          )
        })
      } else return Promise.resolve()
    }
    _clearFlushTimeout() {
      this._timeoutHandle !== void 0 && (clearTimeout(this._timeoutHandle), (this._timeoutHandle = void 0))
    }
    writeRecord(e) {
      if (this.closed) throw new Error('writeApi: already closed!')
      this.writeBuffer.add(e)
    }
    writeRecords(e) {
      if (this.closed) throw new Error('writeApi: already closed!')
      for (let t = 0; t < e.length; t++) this.writeBuffer.add(e[t])
    }
    writePoint(e) {
      if (this.closed) throw new Error('writeApi: already closed!')
      let t = e.toLineProtocol(this)
      t && this.writeBuffer.add(t)
    }
    writePoints(e) {
      if (this.closed) throw new Error('writeApi: already closed!')
      for (let t = 0; t < e.length; t++) {
        let n = e[t].toLineProtocol(this)
        n && this.writeBuffer.add(n)
      }
    }
    async flush(e) {
      if ((await this.writeBuffer.flush(), e)) return await this.retryBuffer.flush()
    }
    close() {
      return this.writeBuffer.flush().finally(() => {
        let t = this.retryBuffer.close()
        t && m.error(`Retry buffer closed with ${t} items that were not written to InfluxDB!`, null), (this.closed = !0)
      })
    }
    dispose() {
      return this._clearFlushTimeout(), (this.closed = !0), this.retryBuffer.close() + this.writeBuffer.length
    }
    useDefaultTags(e) {
      return (this.defaultTags = e), this
    }
    convertTime(e) {
      return e === void 0
        ? this.currentTime()
        : typeof e == 'string'
        ? e.length > 0
          ? e
          : void 0
        : e instanceof Date
        ? this.dateToProtocolTimestamp(e)
        : String(typeof e == 'number' ? Math.floor(e) : e)
    }
  }
function Y(r = {}) {
  let e = 0,
    t = {
      next: n => {
        if (e === 0 && r.next && n !== null && n !== void 0) return r.next(n)
      },
      error: n => {
        e === 0 && ((e = 1), r.error && r.error(n))
      },
      complete: () => {
        e === 0 && ((e = 2), r.complete && r.complete())
      },
      responseStarted: (n, i) => {
        r.responseStarted && r.responseStarted(n, i)
      }
    }
  return (
    r.useCancellable && (t.useCancellable = r.useCancellable.bind(r)),
    r.useResume && (t.useResume = r.useResume.bind(r)),
    t
  )
}
function B(r) {
  let e = {}
  return (
    r.headers.forEach((t, n) => {
      let i = e[n]
      i === void 0 ? (e[n] = t) : Array.isArray(i) ? i.push(t) : (e[n] = [i, t])
    }),
    e
  )
}
var A = class {
  constructor(e) {
    this.connectionOptions = e
    this.chunkCombiner = b()
    this.requestDecorator = function () {}
    ;(this.defaultHeaders = { 'content-type': 'application/json; charset=utf-8', ...e.headers }),
      this.connectionOptions.token && (this.defaultHeaders.Authorization = 'Token ' + this.connectionOptions.token),
      (this.url = String(this.connectionOptions.url)),
      this.url.endsWith('/') && (this.url = this.url.substring(0, this.url.length - 1)),
      this.url.endsWith('/api/v2') &&
        ((this.url = this.url.substring(0, this.url.length - 7)),
        m.warn(`Please remove '/api/v2' context path from InfluxDB base url, using ${this.url} !`))
  }
  send(e, t, n, i) {
    let s = Y(i),
      o = !1,
      a = n.signal,
      l,
      u = () => {},
      f = u
    if (i && i.useCancellable) {
      let c = new AbortController()
      a || ((a = c.signal), (n = { ...n, signal: a })),
        a.addEventListener('abort', () => {
          f()
        }),
        i.useCancellable({
          cancel() {
            ;(o = !0), c.abort()
          },
          isCancelled() {
            return o || a.aborted
          }
        })
    }
    this.fetch(e, t, n)
      .then(async c => {
        if (
          (i != null && i.responseStarted && s.responseStarted(B(c), c.status),
          await this.throwOnErrorResponse(c),
          c.body)
        ) {
          let d = c.body.getReader(),
            g
          do {
            if ((l && (await l), o)) break
            if (((g = await d.read()), s.next(g.value) === !1)) {
              let D = s.useResume
              if (!D) {
                let E = 'Unable to pause, useResume is not configured!'
                return await d.cancel(E), Promise.reject(new Error(E))
              }
              l = new Promise(E => {
                ;(f = () => {
                  E(), (l = void 0), (f = u)
                }),
                  D(f)
              })
            }
          } while (!g.done)
        } else if (c.arrayBuffer) {
          let d = await c.arrayBuffer()
          s.next(new Uint8Array(d))
        } else {
          let d = await c.text()
          s.next(new TextEncoder().encode(d))
        }
      })
      .catch(c => {
        o || s.error(c)
      })
      .finally(() => s.complete())
  }
  async throwOnErrorResponse(e) {
    if (e.status >= 300) {
      let t = ''
      try {
        if (((t = await e.text()), !t)) {
          let n = e.headers.get('x-influxdb-error')
          n && (t = n)
        }
      } catch (n) {
        throw (
          (m.warn('Unable to receive error body', n),
          new h(
            e.status,
            e.statusText,
            void 0,
            e.headers.get('retry-after'),
            e.headers.get('content-type'),
            void 0,
            B(e)
          ))
        )
      }
      throw new h(e.status, e.statusText, t, e.headers.get('retry-after'), e.headers.get('content-type'), void 0, B(e))
    }
  }
  async *iterate(e, t, n) {
    var s
    let i = await this.fetch(e, t, n)
    if ((await this.throwOnErrorResponse(i), i.body)) {
      let o = i.body.getReader()
      for (;;) {
        let { value: a, done: l } = await o.read()
        if (l) break
        if ((s = n.signal) != null && s.aborted) throw (await i.body.cancel(), new L())
        yield a
      }
    } else if (i.arrayBuffer) {
      let o = await i.arrayBuffer()
      yield new Uint8Array(o)
    } else {
      let o = await i.text()
      yield new TextEncoder().encode(o)
    }
  }
  async request(e, t, n, i) {
    var u, f
    let s = await this.fetch(e, t, n),
      { headers: o } = s,
      a = o.get('content-type') || ''
    i && i(B(s), s.status), await this.throwOnErrorResponse(s)
    let l = (f = (u = n.headers) == null ? void 0 : u.accept) != null ? f : a
    if (l.includes('json')) return await s.json()
    if (l.includes('text') || l.startsWith('application/csv')) return await s.text()
  }
  fetch(e, t, n) {
    let { method: i, headers: s, ...o } = n,
      a = `${this.url}${e}`,
      l = {
        method: i,
        body: i === 'GET' || i === 'HEAD' ? void 0 : typeof t == 'string' ? t : JSON.stringify(t),
        headers: { ...this.defaultHeaders, ...s },
        credentials: 'omit',
        ...this.connectionOptions.transportOptions,
        ...o
      }
    return this.requestDecorator(l, n, a), fetch(a, l)
  }
}
var we = {
    header: !0,
    delimiter: ',',
    quoteChar: '"',
    commentPrefix: '#',
    annotations: ['datatype', 'group', 'default']
  },
  Z = class r {
    constructor(e, t, n) {
      this.transport = e
      this.createCSVResponse = t
      this.options = typeof n == 'string' ? { org: n } : n
    }
    with(e) {
      return new r(this.transport, this.createCSVResponse, { ...this.options, ...e })
    }
    response(e) {
      let { org: t, type: n, gzip: i, headers: s } = this.options,
        o = `/api/v2/query?org=${encodeURIComponent(t)}`,
        a = JSON.stringify(this.decorateRequest({ query: e.toString(), dialect: we, type: n })),
        l = {
          method: 'POST',
          headers: {
            'content-type': 'application/json; encoding=utf-8',
            'accept-encoding': i ? 'gzip' : 'identity',
            ...s
          }
        }
      return this.createCSVResponse(
        u => this.transport.send(o, a, l, u),
        () => this.transport.iterate(o, a, l)
      )
    }
    iterateLines(e) {
      return this.response(e).iterateLines()
    }
    iterateRows(e) {
      return this.response(e).iterateRows()
    }
    lines(e) {
      return this.response(e).lines()
    }
    rows(e) {
      return this.response(e).rows()
    }
    queryLines(e, t) {
      return this.response(e).consumeLines(t)
    }
    queryRows(e, t) {
      return this.response(e).consumeRows(t)
    }
    collectRows(e, t) {
      return this.response(e).collectRows(t)
    }
    collectLines(e) {
      return this.response(e).collectLines()
    }
    queryRaw(e) {
      let { org: t, type: n, gzip: i, headers: s } = this.options
      return this.transport.request(
        `/api/v2/query?org=${encodeURIComponent(t)}`,
        JSON.stringify(this.decorateRequest({ query: e.toString(), dialect: we, type: n })),
        {
          method: 'POST',
          headers: {
            accept: 'text/csv',
            'accept-encoding': i ? 'gzip' : 'identity',
            'content-type': 'application/json; encoding=utf-8',
            ...s
          }
        }
      )
    }
    decorateRequest(e) {
      var t
      return (
        typeof this.options.now == 'function' && (e.now = this.options.now()),
        (e.type = (t = this.options.type) != null ? t : 'flux'),
        e
      )
    }
  },
  Re = Z
function Ie(r, e) {
  return e.toObject(r)
}
var M = class {
  constructor(e, t, n) {
    this.executor = e
    this.iterableResultExecutor = t
    this.chunkCombiner = n
  }
  iterateLines() {
    return H(this.iterableResultExecutor())
  }
  iterateRows() {
    return ne(H(this.iterableResultExecutor()))
  }
  lines() {
    return new T(this.executor, e => R(e, this.chunkCombiner))
  }
  rows() {
    return new T(this.executor, e =>
      R(
        W({
          next(t, n) {
            e.next({ values: t, tableMeta: n })
          },
          error(t) {
            e.error(t)
          },
          complete() {
            e.complete()
          }
        }),
        this.chunkCombiner
      )
    )
  }
  consumeLines(e) {
    this.executor(R(e, this.chunkCombiner))
  }
  consumeRows(e) {
    this.executor(R(W(e), this.chunkCombiner))
  }
  collectRows(e = Ie) {
    let t = []
    return new Promise((n, i) => {
      this.consumeRows({
        next(s, o) {
          let a = e.call(this, s, o)
          a !== void 0 && t.push(a)
        },
        error(s) {
          i(s)
        },
        complete() {
          n(t)
        }
      })
    })
  }
  collectLines() {
    let e = []
    return new Promise((t, n) => {
      this.consumeLines({
        next(i) {
          e.push(i)
        },
        error(i) {
          n(i)
        },
        complete() {
          t(e)
        }
      })
    })
  }
}
var _ = class {
  constructor(e) {
    var n
    if (typeof e == 'string') this._options = { url: e }
    else if (e !== null && typeof e == 'object') this._options = Object.assign({}, e)
    else throw new y('No url or configuration specified!')
    let t = this._options.url
    if (typeof t != 'string') throw new y('No url specified!')
    t.endsWith('/') && (this._options.url = t.substring(0, t.length - 1)),
      (this.transport = (n = this._options.transport) != null ? n : new A(this._options)),
      delete this._options.token,
      (this.processCSVResponse = (i, s) => new M(i, s, this.transport.chunkCombiner))
  }
  getWriteApi(e, t, n = 'ns', i) {
    return new v(this.transport, e, t, n, i != null ? i : this._options.writeOptions)
  }
  getQueryApi(e) {
    return new Re(this.transport, this.processCSVResponse, e)
  }
}
export {
  L as AbortError,
  Nt as DEFAULT_ConnectionOptions,
  se as DEFAULT_RetryDelayStrategyOptions,
  oe as DEFAULT_WriteOptions,
  $ as FLUX_VALUE,
  h as HttpError,
  y as IllegalArgumentError,
  _ as InfluxDB,
  x as LineSplitter,
  m as Log,
  xe as Point,
  te as RequestTimedOutError,
  ee as UNKNOWN_COLUMN,
  Ne as canRetryHttpCall,
  R as chunksToLines,
  H as chunksToLinesIterable,
  Ee as consoleLogger,
  pe as convertTimeToNanos,
  We as createFluxTableColumn,
  I as createFluxTableMetaData,
  b as createTextDecoderCombiner,
  de as currentTime,
  me as dateToProtocolTimestamp,
  w as escape,
  nr as flux,
  rr as fluxBool,
  Zt as fluxDateTime,
  er as fluxDuration,
  he as fluxExpression,
  Kt as fluxFloat,
  Yt as fluxInteger,
  tr as fluxRegExp,
  Gt as fluxString,
  re as getRetryDelay,
  Oe as isStatusCodeRetriable,
  ne as linesToRowsIterable,
  W as linesToTables,
  F as newFluxTableColumn,
  ye as sanitizeFloat,
  ge as sanitizeInteger,
  Xe as serializeDateTimeAsDate,
  Ge as serializeDateTimeAsNumber,
  Ke as serializeDateTimeAsString,
  Jt as setLogger,
  pt as stringToLines,
  ie as symbolObservable,
  J as toFluxValue,
  C as typeSerializers,
  De as useProcessHrtime
}
//# sourceMappingURL=index.browser.mjs.map
